package org.example.iris.service.impl;

import org.example.iris.dto.JobInfo;
import org.example.iris.dto.RecommendCompanyInfo;
import org.example.iris.mapper.CompanyMapper;
import org.example.iris.mapper.EnrollMapper;
import org.example.iris.mapper.JobMapper;
import org.example.iris.mapper.UserMapper;
import org.example.iris.entity.*;
import org.example.iris.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private EnrollMapper enrollMapper; // 添加这一行

    @Override
    public List<RecommendCompanyInfo> recommendCompany() {
        List<Company> companies = companyMapper.recommendCompany();
        List<RecommendCompanyInfo> recommendCompanyInfos = new ArrayList<>();
        for (Company company : companies) {
            RecommendCompanyInfo recommendCompanyInfo = new RecommendCompanyInfo();
            Integer companyId = company.getCompanyId();
            List<JobInfo> jobInfo = jobMapper.selectThreeByCompanyId(companyId);
            for (JobInfo job : jobInfo) {
                job.setTag(List.of(job.getRequirement().replace("[", "")
                        .replace("]", "")
                        .replace("'", "")
                        .split(", ")));
            }
            recommendCompanyInfo.setCompanyId(company.getCompanyId());
            recommendCompanyInfo.setUserId(company.getUserId());
            recommendCompanyInfo.setCompanyName(company.getCompanyName());
            recommendCompanyInfo.setDescription(company.getDescription());
            recommendCompanyInfo.setCulture(company.getCulture());
            recommendCompanyInfo.setLogo(company.getLogo());
            recommendCompanyInfo.setWebsite(company.getWebsite());
            recommendCompanyInfo.setCity(company.getCity());
            recommendCompanyInfo.setJobInfo(jobInfo);
            recommendCompanyInfos.add(recommendCompanyInfo);
        }
        return recommendCompanyInfos;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean register(User user, Company company) {
        try {
            // 参数校验
            if (user == null || company == null) {
                throw new IllegalArgumentException("User and Company must not be null");
            }

            // 插入 user 表，并获取生成的 userId
            userMapper.insertUser(user);
            User user1 = userMapper.findByUsername(user.getUsername());
            if (user1 == null) {
                throw new RuntimeException("User not found after insertion: " + user.getUsername());
            }
            company.setUserId(user1.getUserId());

            // 插入 company 表
            companyMapper.insert(company);
            Company company1 = companyMapper.getCompanyByUserId(company.getUserId());
            if (company1 == null) {
                throw new RuntimeException("Company not found after insertion: " + company.getUserId());
            }

            // 创建 Enroll 对象并插入记录
            Enroll enroll = new Enroll();
            enroll.setCompanyId(company1.getCompanyId());
            enroll.setStatus("pending"); // 默认 status 为 pending
            enrollMapper.insertEnrollRecord(enroll);

            return true;

        } catch (Exception e) {
            //logger.error("Error occurred during registration: {}", e.getMessage(), e);
            throw e;
        }
    }


    /**
     * 更新企业信息
     * @param company 要更新的企业信息
     * @return 更新是否成功
     */
    @Override
    public boolean updateCompanyInfo(Company company) {
        // 调用 CompanyMapper 的 updateCompanyInfo 方法更新数据
        int result = companyMapper.updateCompanyInfo(company);
        return result > 0;  // 如果更新的记录数大于0，说明更新成功
    }

    @Override
    public List<Company> selectCompany(String keywords) {
        return companyMapper.selectCompany(keywords);
    }

    @Override
    public List<JobInfo> companyJob(Integer companyId) {
        return jobMapper.selectByCompanyId(companyId);
    }

    @Override
    public Company companyInfo(Integer companyId) {
        return companyMapper.findById(companyId);
    }

    @Override
    public Company findByUserId(Integer userId) {
        return companyMapper.findByUserId(userId);
    }

    @Override
    public List<Company> allCompany() {
        return companyMapper.allCompany();
    }

}